package com.ds.service;

import com.ds.config.Constants;
import com.ds.dao.BuildingDao;
import com.ds.model.AjaxPageResult;
import com.ds.model.AjaxResult;
import com.ds.model.BuildingInfo;

import java.sql.SQLException;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class BuildingService {
    private BuildingDao buildingDao = new BuildingDao();
    public AjaxResult addBuilding(BuildingInfo buildingInfo) {
        try {
            buildingInfo.setCreateTime(new Date());
            buildingInfo.setDeleteFlag(Constants.DELETE_FLAG);
            int i = buildingDao.saveBuilding(buildingInfo);
            if (i == 1){
                return AjaxResult.ok("添加成功");
            }
        } catch (Exception e) {

        }
        return AjaxResult.error("添加失败");
    }

    public AjaxPageResult getBuildingList(int page, int limit) {
        AjaxPageResult result = new AjaxPageResult();

        try {
            result.setCode("0");
            result.setCount(buildingDao.getTotal());
            result.setData(buildingDao.getBuildingList((page - 1) * limit,limit));
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return result;
    }

    public AjaxResult deleteBuilding(String[] buildingIds) {
        int result = 0;
        try {
            List<Integer> bids = Arrays.stream(buildingIds).map(i -> Integer.parseInt(i)).collect(Collectors.toList());
            result = buildingDao.deleteBuilding(bids);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return result == buildingIds.length ? AjaxResult.ok("删除成功"):AjaxResult.error("删除失败");
    }

    public AjaxResult updateBuilding(BuildingInfo buildingInfo) {
        buildingInfo.setUpdateTime(new Date());
        int result = 0;
        try {
            result = buildingDao.updateBuilding(buildingInfo);
        } catch (SQLException e) {
            e.printStackTrace();
        }

        return result == 1 ? AjaxResult.ok("更新成功"):AjaxResult.error("更新失败");
    }
}
